import pyaudio
import numpy as np
import time
from datetime import datetime
from multiprocessing import Process, Queue

# 音频参数
FORMAT = pyaudio.paInt16   # 数据格式
CHANNELS = 1               # 单声道
RATE = 44100               # 采样率
CHUNK = 1024               # 每次读取的帧数

# 创建PyAudio对象
p = pyaudio.PyAudio()

# 打开流
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK,
                input_device_index=1,  # 指定设备的index值
                )

def calculate_decibel(data):
    # 将音频数据转换成numpy数组
    samples = np.frombuffer(data, dtype=np.int16)
    # 计算振幅
    peak_amplitude = np.abs(samples).max()
    # 计算分贝
    if peak_amplitude == 0:
        return -np.inf  # 分贝值为负无穷
    else:
        return 20 * np.log10(peak_amplitude / 32768.0)  # 32768是Int16的最大值

try:
    while True:
        # 读取音频数据
        data = stream.read(CHUNK)
        # 计算分贝
        db_value = calculate_decibel(data)
        print(datetime.now(),f"#{(db_value+90+12+1.2):.2f} dB")
        time.sleep(0.3)
except KeyboardInterrupt:
    # 当按下Ctrl+C时退出
    print("停止录音")
finally:
    # 关闭流和PyAudio对象
    stream.stop_stream()
    stream.close()
    p.terminate()